package org.mcb.zebra.portal.tag;

import java.io.IOException;

import javax.portlet.PortletException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.pluto.PortletContainer;
import org.apache.pluto.PortletContainerException;
import org.apache.pluto.PortletWindow;
import org.mcb.zebra.portal.manager.PortalManager;
import org.mcb.zebra.portal.page.Page;
import org.mcb.zebra.portal.page.PageManager;

@SuppressWarnings("serial")
public class PortletTag extends TagSupport {
	private String portletWindowID;
	public String getPortletWindowID() {
		return portletWindowID;
	}
	public void setPortletWindowID(String portletWindowID) {
		this.portletWindowID = portletWindowID;
	}
	@Override
	public int doStartTag() throws JspException {
		ServletContext context =pageContext.getServletContext();
		PortletContainer container =(PortletContainer) context.getAttribute(PortalManager.PORTLET_CONTAINER);
		PortalManager portalManager = (PortalManager) context.getAttribute(PortalManager.PORTAL_MANAGER);
		if(container!=null){
			if(portletWindowID!=null){
				PageManager pageManager = portalManager.getPageManager();
				String pageName = (String) pageContext.getRequest().getAttribute(PageManager.CURRENT_PAGE);
				Page page = pageManager.getPage(pageName);
				if(page!=null){
					PortletWindow portletWindow = page.getPortletWindow(portletWindowID);
					try {
						container.doRender(portletWindow,(HttpServletRequest)this.pageContext.getRequest() ,(HttpServletResponse)this.pageContext.getResponse());
					} catch (PortletException e) {
						throw new JspException(e);
					} catch (IOException e) {
						throw new JspException(e);
						
					} catch (PortletContainerException e) {
						throw new JspException(e);
					}
				}
			}
		}		
		return TagSupport.EVAL_BODY_INCLUDE;
	}
	@Override
	public int doEndTag() throws JspException {
		// TODO Auto-generated method stub
		return super.doEndTag();
	}
}
